﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.Numerics;

namespace SSPComm.SSPCryption
{
    internal class SSPEncryptor
    {
        internal readonly BigInteger Generator;// = 139791917;
        internal readonly BigInteger Modulus;// = 769202429

        private readonly AesManaged _aesManaged = new AesManaged();
        private ICryptoTransform _transCry = null;
        private ICryptoTransform _transDec = null;
        private readonly BigInteger _hostSecret;
        private readonly Int32 PRIME_LEN = 4;

        public SSPEncryptor()
        {
            Random rnd = new Random(DateTime.Now.Millisecond);
            _hostSecret = new BigInteger(rnd.Next(0x00, 0xFFFFFFF));

            Int32 mod = rnd.Next(5, (MainResource.primes.Length / PRIME_LEN) - 1);
            Int32 gen = rnd.Next(1, mod);

            Modulus = (UInt64)BitConverter.ToUInt32(MainResource.primes, mod * PRIME_LEN);
            Generator = (UInt64)BitConverter.ToUInt32(MainResource.primes, gen * PRIME_LEN);
        }

        internal BigInteger HostExchangeKey
        {
            get
            {
                return BigInteger.ModPow(Generator, _hostSecret, Modulus);
            }
        }

        internal void SolveKey(UInt64 inKey)
        {
            if (inKey == 0)
            {
                throw new ArgumentException("key is 0");
            }

            _aesManaged.BlockSize = 128;
            _aesManaged.IV = new Byte[16];
            _aesManaged.KeySize = 128;
            _aesManaged.Mode = CipherMode.ECB;
            _aesManaged.Padding = PaddingMode.None;//ISO10126;

            Byte[] synchKey = new Byte[16];

            UInt64 keyGen = inKey;
                //(UInt64)GetKey(BitConverter.GetBytes(inExchangeKey), _hostSecret, Modulus);
            UInt64 keyFix = 0x0123456701234567;

            Byte[] tempH = new Byte[8];
            tempH = BitConverter.GetBytes(keyGen);

            Byte[] tempL = new Byte[8];
            tempL = BitConverter.GetBytes(keyFix);


            Array.Copy(tempH, 0, synchKey, 8, 8);
            Array.Copy(tempL, 0, synchKey, 0, 8);

            _aesManaged.Key = synchKey;
            _transCry = _aesManaged.CreateEncryptor();
            _transDec = _aesManaged.CreateDecryptor();
        }

        internal void SolveSynchKey(UInt64 inExchangeKey)
        {
            if (inExchangeKey == 0)
            {
                throw new ArgumentException("Slave exchange key is 0");
            }

            _aesManaged.BlockSize = 128;
            _aesManaged.IV = new Byte[16];
            _aesManaged.KeySize = 128;
            _aesManaged.Mode = CipherMode.ECB;
            _aesManaged.Padding = PaddingMode.None;
                //ISO10126;

            Byte[] synchKey = new Byte[16];

            Byte[] keyGen = BigInteger.ModPow(new BigInteger(inExchangeKey), _hostSecret, Modulus).ToByteArray();
            //(UInt64)GetKey(BitConverter.GetBytes(inExchangeKey), _hostSecret, Modulus);
            UInt64 keyFix = 0x0123456701234567;

            Byte[] tempH = new Byte[8];
            if (keyGen.Length <= 8)
            {
                Array.Copy(keyGen, 0, tempH, 0, keyGen.Length);
            }
            else
            {
                Array.Copy(keyGen, keyGen.Length - 8, tempH, 0, 8);
            }

            Byte[] tempL = new Byte[8];
            tempL = BitConverter.GetBytes(keyFix);


            Array.Copy(tempH, 0, synchKey, 8, 8);
            Array.Copy(tempL, 0, synchKey, 0, 8);

            _aesManaged.Key = synchKey;
            _transCry = _aesManaged.CreateEncryptor();
            _transDec = _aesManaged.CreateDecryptor();
        }

        internal Byte[] Crypt(byte[] inputBuffer)
        {
            if (_transCry == null)
            {
                throw new NullReferenceException("_cryTrans is null");
            }
            Byte[] outputBuffer = _transCry.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
                //new Byte[128];
            //int len = _transCry.TransformBlock(inputBuffer, 0, inputBuffer.Length, outputBuffer, 0);
            //Byte[] result = new Byte[len];
            //Array.Copy(outputBuffer, result, len);
            return outputBuffer;
        }

        internal Byte[] Decrypt(byte[] inputBuffer)
        {
            if (_transDec == null)
            {
                throw new NullReferenceException("_transDec is null");
            }
            Byte[] outputBuffer;// = new Byte[128];
            //int len = _transDec.TransformBlock(inputBuffer, 0, inputBuffer.Length, outputBuffer, 0);
            outputBuffer = _transDec.TransformFinalBlock(inputBuffer, 0, inputBuffer.Length);
            //TransformBlock(inputBuffer, 0, inputBuffer.Length, outputBuffer, 0);
            //Byte[] result = new Byte[len];
           //. Array.Copy(outputBuffer, result, len);
            //return result;
            return outputBuffer;
        }
    }

    #if DEBUG
    namespace Testing
    {
        using NUnit.Framework;
        using System.Diagnostics;
        [TestFixture]
        public class SSPEncryptorTest
        {
            [Test]
            public void CryptDecrypt()
            {
                SSPEncryptor enc = new SSPEncryptor();
                enc.SolveKey(0x00000000289f278a);
                //enc.Decrypt(new Byte[] { 0x62, 0x03, 0xA3, 0xCC, 0xD9, 0x9A, 0x68, 0xA4, 0x84, 0x08, 0xBB, 0x09, 0x83, 0x2B, 0xEF, 0xFE });
                Byte[] res;

                //request 0
                res = enc.Crypt(new Byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x30, 0x05, 0x44, 0x2b, 0xd0, 0xa2, 0xad, 0xe2, 0x0e, 0x09, 0xed });
                Assert.AreEqual(new Byte[] { 0xF1, 0x03, 0x14, 0x44, 0xB9, 0x1F, 0xAC, 0xD0, 0x42, 0xA8, 0xF0, 0x1A, 0x5B, 0x69, 0x6A, 0x18 }, res);
                //res = enc.Decrypt(new Byte[] { 0xF1, 0x03, 0x14, 0x44, 0xB9, 0x1F, 0xAC, 0xD0, 0x42, 0xA8, 0xF0, 0x1A, 0x5B, 0x69, 0x6A, 0x18 });
                //Assert.AreEqual(new Byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x30, 0x05, 0x44, 0x2b, 0xd0, 0xa2, 0xad, 0xe2, 0x0e, 0x09, 0xed }, res);

                //reply 1
                res = enc.Decrypt(new Byte[] { 0x52, 0x76, 0xB1, 0xB9, 0x10, 0xFA, 0x2F, 0xB8, 0x4D, 0x3D, 0x80, 0x60, 0x70, 0xEC, 0xF3, 0x91, 0xDB, 0x53, 0xBA, 0xDE, 0x03, 0xEF, 0x13, 0x79, 0xC6, 0x56, 0x27, 0x10, 0x62, 0xA0, 0xD7, 0x87 });
                Assert.AreEqual(new Byte[] { 0x11, 0x01, 0x00, 0x00, 0x00, 0xf0, 0x53, 0x48, 0x30, 0x30, 0x30, 0x33, 0x36, 0x30, 0x34, 0x31, 0x32, 0x33, 0x31, 0x30, 0x30, 0x30, 0xc6, 0x1f, 0x5a, 0xf0, 0xe9, 0xbe, 0xed, 0x7f, 0x0f, 0x0c }, res);

                //request 1
                res = enc.Crypt(new Byte[] { 0x01, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x2b, 0xd0, 0xa2, 0xad, 0xe2, 0x0e, 0x0a, 0x3f, 0xf1, 0xb9 });
                Assert.AreEqual(new Byte[] { 0xEF, 0xCB, 0xA7, 0x1C, 0xA8, 0xEF, 0xB6, 0xD8, 0x34, 0x94, 0x68, 0xC2, 0xA7, 0x73, 0xA6, 0x83 }, res);
                //res = enc.Decrypt(new Byte[] { 0xEF, 0xCB, 0xA7, 0x1C, 0xA8, 0xEF, 0xB6, 0xD8, 0x34, 0x94, 0x68, 0xC2, 0xA7, 0x73, 0xA6, 0x83 });
                //Assert.AreEqual(new Byte[] { 0x01, 0x01, 0x00, 0x00, 0x00, 0x0c, 0x2b, 0xd0, 0xa2, 0xad, 0xe2, 0x0e, 0x0a, 0x3f, 0xf1, 0xb9 }, res);

                //reply 2
                res = enc.Decrypt(new Byte[] { 0x08, 0xDC, 0x18, 0x25, 0x72, 0xF9, 0x54, 0x2D, 0xB6, 0x6B, 0xF5, 0xE5, 0xE2, 0x6F, 0x27, 0x2C });
                Assert.AreEqual(new Byte[] { 0x05, 0x02, 0x00, 0x00, 0x00, 0xf0, 0x00, 0x07, 0xb4, 0x34, 0xeb, 0x33, 0xde, 0x64, 0xa2, 0x19 }, res);

                //res = enc.Decrypt(new Byte[] { 0x62, 0x03, 0xA3, 0xCC, 0xD9, 0x9A, 0x68, 0xA4, 0x84, 0x08, 0xBB, 0x09, 0x83, 0x2B, 0xEF, 0xFE });
                //Assert.AreEqual(new Byte[] { 0x04, 0x11, 0x00, 0x00, 0x00, 0x3e, 0x52, 0x55, 0x42, 0x2b, 0xd0, 0xa2, 0xad, 0xe2, 0x31, 0x73 }, res);

                //res = enc.Decrypt(new Byte[]{ 0xF9, 0x88, 0x3F, 0x54, 0xD0, 0x53, 0xA2, 0x9F, 0xCD, 0x09, 0xDE, 0x27, 0xB1, 0xA2, 0xB7, 0x89});
                //Assert.AreEqual(new Byte[] {0x04,0x11,0x00,0x00,0x00,0x3e,0x52,0x55,0x42,0x2b,0xd0,0xa2,0xad,0xe2,0x31,0x73 }, res);

                //res = enc.Decrypt(new Byte[]{0x41 , 0x29 , 0x42 , 0x10 , 0xC8 , 0x56 , 0x82 , 0xAF , 0x3F , 0x16 , 0xFF , 0x2B , 0x49 , 0x34 , 0xDD, 0x2B});
                //Assert.AreEqual(new Byte[] {0x05,0x12,0x00,0x00,0x00,0xf0,0x0a,0x00,0x00,0x00,0x48,0xc0,0x13,0xc2,0x35,0xb2 }, res);

                //res = enc.Decrypt(new Byte[] { 0x18, 0xFC, 0xE6, 0xAB, 0x3A, 0x3E, 0x45, 0xA1, 0xCA, 0xF1, 0xCC, 0xD4, 0x23, 0xE9, 0x68, 0x67 });
                //Assert.AreEqual(new Byte[] {0x01,0x12,0x00,0x00,0x00,0x0a,0x93,0xa3,0x73,0x60,0x2b,0x66,0x2c,0xc5,0x21,0x9e}, res);
            }

            [Test]
            public void Decrypt()
            {
                SSPEncryptor enc = new SSPEncryptor();
                enc.SolveKey(0x00000000289f278a);
                //enc.Decrypt(new Byte[] { 0x62, 0x03, 0xA3, 0xCC, 0xD9, 0x9A, 0x68, 0xA4, 0x84, 0x08, 0xBB, 0x09, 0x83, 0x2B, 0xEF, 0xFE });
                Byte[] res;
                for (int i = 0; i < 10; i++)
                {
                    Debug.Print(i.ToString());
                    res = enc.Decrypt(new Byte[] { 0x52, 0x76, 0xB1, 0xB9, 0x10, 0xFA, 0x2F, 0xB8, 0x4D, 0x3D, 0x80, 0x60, 0x70, 0xEC, 0xF3, 0x91, 0xDB, 0x53, 0xBA, 0xDE, 0x03, 0xEF, 0x13, 0x79, 0xC6, 0x56, 0x27, 0x10, 0x62, 0xA0, 0xD7, 0x87 });
                    Assert.AreEqual(new Byte[] { 0x11, 0x01, 0x00, 0x00, 0x00, 0xf0, 0x53, 0x48, 0x30, 0x30, 0x30, 0x33, 0x36, 0x30, 0x34, 0x31, 0x32, 0x33, 0x31, 0x30, 0x30, 0x30, 0xc6, 0x1f, 0x5a, 0xf0, 0xe9, 0xbe, 0xed, 0x7f, 0x0f, 0x0c }, res);
                }

                //AesManaged man = new AesManaged();
                //man.Mode = CipherMode.ECB;
                //man.KeySize = 128;
                //man.BlockSize = 128;
                //man.Padding = PaddingMode.None;
                //man.Key = new Byte[]{ 0x67,0x45,0x23,0x01,0x67,0x45,0x23,0x01,0x07,0x3b,0x4a,0x12,0x00,0x00,0x00,0x00};
                //ICryptoTransform dec = man.CreateDecryptor();
                //Byte[] input = new Byte[] { 0x1e, 0x59, 0x41, 0x40, 0x9b, 0x38, 0xa0, 0x0e, 0x98, 0x0e, 0x94, 0xb6, 0x6e, 0x2c, 0xf6, 0x94 };
                //Byte[] output = new Byte[255];
                ////int len = dec.TransformBlock(input, 0, input.Length, output, 0);
                //output = dec.TransformFinalBlock(input, 0, input.Length);
                ////Assert.AreEqual(16, len);
            }

            [Test]
            public void Crypt()
            {
                SSPEncryptor enc = new SSPEncryptor();
                enc.SolveKey(0x00000000289f278a);
                //enc.Decrypt(new Byte[] { 0x62, 0x03, 0xA3, 0xCC, 0xD9, 0x9A, 0x68, 0xA4, 0x84, 0x08, 0xBB, 0x09, 0x83, 0x2B, 0xEF, 0xFE });
                Byte[] res;
                for (int i = 0; i < 10; i++)
                {
                    Debug.Print(i.ToString());
                    res = enc.Crypt(new Byte[] { 0x03, 0x00, 0x00, 0x00, 0x00, 0x30, 0x05, 0x44, 0x2b, 0xd0, 0xa2, 0xad, 0xe2, 0x0e, 0x09, 0xed });
                    Assert.AreEqual(new Byte[] { 0xF1, 0x03, 0x14, 0x44, 0xB9, 0x1F, 0xAC, 0xD0, 0x42, 0xA8, 0xF0, 0x1A, 0x5B, 0x69, 0x6A, 0x18 }, res);
                }
            }
        }
    }
#endif
}
